package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author atguigu-mqx
 */
@Service
public class ManageServiceImpl implements ManageService {

    //  调用mapper 层！
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;




    @Override
    public List<BaseCategory1> getCategory1() {
        //  select * from base_category1
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where category1_id = category1Id
        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        return baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  select * from base_category3 where category2_id = category2Id
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));
    }

    //  根据分类Id 查询数据：平台属性
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //  根据分析可能需要具备的知识点：mybatis的动态sql 标签！
        //  多表关联查询：因此 使用*Mapper.xml
        //  开发的默认规则： service 层 ；get  save mapper层；select insert
        return baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 有异常就回滚！
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  这个控制器 ，有添加功能，也有修改功能！ base_attr_info
        if (baseAttrInfo.getId()==null){
            //  插入数据：
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else {
            //  修改数据
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //  base_attr_value 先删除，再新增！
        //  delete from base_attr_value where attr_id = ?;
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);

        //  获取平台属性值集合数据
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  普通循环
        for (BaseAttrValue baseAttrValue : attrValueList) {
            //  attrId 传递的时候是null
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //  直接返回数据
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id",attrId));
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //  select * from base_attr_info where id = attrId;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //  给attrValueList 赋值！
        if (baseAttrInfo!=null){
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        //  返回数据！
        return baseAttrInfo;
    }

    @Override
    public IPage getSpuInfoPage(Page iPage, SpuInfo spuInfo) {
        //  select * from spu_info where category3_id = 61 order by id desc limit 0 , 10;
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        spuInfoQueryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(iPage,spuInfoQueryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        //  select * from base_sale_attr;
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        /*
        spuInfo;	商品表
        spuImage;	商品图片表
        spuSaleAttr;	销售属性
        spuSaleAttrValue;	销售属性值
        spuPoster;	商品海报
         */
        spuInfoMapper.insert(spuInfo);
        //  商品图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //  判断
        if (!CollectionUtils.isEmpty(spuImageList)){
            //  循环遍历
            spuImageList.stream().forEach((spuImage -> {
                //  你是怎么知道spuId 为 null
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }));
        }

        //  销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //  判断
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.stream().forEach((spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //  获取销售属性值集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        //  赋值
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            }));
        }

        //  spuPoster 海报
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.stream().forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }

    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //  调用mapper ，多表关联！
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
            将数据插入数据库表！
            skuInfo:	库存单元表！	记录是哪个spu下的sku!
            skuImage:	库存单元图片表!
            skuSaleAttrValue;	sku 与 销售属性值中间表！
            skuAttrValue:	sku 与平台属性值中间表！
         */
        skuInfoMapper.insert(skuInfo);

        //  获取skuImage 集合
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        //  判断
        if (!CollectionUtils.isEmpty(skuImageList)) {
            skuImageList.stream().forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //  skuAttrValue
        if (!CollectionUtils.isEmpty(skuInfo.getSkuAttrValueList())) {
            skuInfo.getSkuAttrValueList().stream().forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                //  应该能够获取到平台属性名，平台属性值名！
                //  应该页面自动获取！   查询：category3Id 查询到平台属性名！但是绝对找不到要给的属性值名称！
                //  经过分析：可以不用赋值attrName valueName;
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //  skuSaleAttrValue
        if (!CollectionUtils.isEmpty(skuInfo.getSkuSaleAttrValueList())) {
            skuInfo.getSkuSaleAttrValueList().stream().forEach(skuSaleAttrValue -> {
                //  spuId，skuId
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    @Override
    public IPage getList(Page<SkuInfo> skuInfoPage) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage,skuInfoQueryWrapper);
    }

    @Override
    public void onSale(Long skuId) {
        //  update sku_info set is_sale = 1 where id = skuId;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
    }

    @Override
    public void cancelSale(Long skuId) {
        //  update sku_info set is_sale = 0 where id = skuId;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //  获取skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //  需要skuImageList
        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));

        skuInfo.setSkuImageList(skuImageList);

        return skuInfo;
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        //  select price from sku_info where id = skuId;
        //  select * from sku_info where id = skuId;
        //  SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.eq("id",skuId);
        skuInfoQueryWrapper.select("price");
        SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
        //  返回价格
        return skuInfo.getPrice();
    }

    @Override
    public BaseCategoryView getCategoryName(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        //返回数据
        return baseCategoryView;
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListById(Long skuId, Long spuId) {
        //返回数据
        return spuSaleAttrMapper.selectSpuSaleAttrListById(skuId,spuId);
    }

    @Override
    public Map getValueIdsAndSkuIdToMap(Long spuId) {
        //  声明map 集合
        HashMap<Object, Object> hashMap = new HashMap<>();
        //  获取销售属性值Id 与skuId ！
        //  执行sql 语句获取到
        List<Map> mapList = skuSaleAttrValueMapper.selectValueIdsAndSkuIdToMap(spuId);
        // select * from base_category1; List<BaseCategory1>  base.setName(name);
        if (!CollectionUtils.isEmpty(mapList)){
            mapList.stream().forEach((map->{
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            }));
        }
        //  返回数据
        return hashMap;
    }

    @Override
    public List<SpuPoster> getSpuPosterList(Long spuId) {
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id",spuId));
    }

    @Override
    public List<BaseAttrInfo> getBaseAttrInfoList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(skuId);
    }

}
